const scriptListMap = new Map<string, Promise<void> | null>()

/**
 * 刪除script脚本url上的?后面的参数，只保留实际url
 * @param src
 * @returns
 */
const handleScriptUrl = (src = '') => {
  // 去除?的影响
  src = src.substring(0, src.indexOf('?') !== -1 ? src.indexOf('?') : src.length)
  return src
}

/**
 * 加载js脚本（已经加载过的脚本资源不会二次加载）
 * @param src
 * @returns
 */
export const loadScript = async (src: string) => {
  const cacheKey = handleScriptUrl(src)
  let promise = scriptListMap.get(cacheKey)
  if (!promise) {
    promise = new Promise((resolve, reject) => {
      const scriptDom = document.createElement('script')
      scriptDom.type = 'text/javascript'
      scriptDom.onload = () => {
        resolve()
      }
      scriptDom.onerror = () => {
        reject()
        // 同时重置对应脚本src对应的promise，让后续如果再次加载时重新加载script脚本
        scriptListMap.set(cacheKey, null)
        document.head.removeChild(scriptDom)
      }
      scriptDom.src = src
      document.head.appendChild(scriptDom)
    })
  }
  scriptListMap.set(cacheKey, promise)
  return promise
}

/** 加载声网sdk */
/* export const loadAgoraScript = () => {
  return loadScript(AppendEduScriptPath)
} */
